package com.shijie99.paper.manage.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.shijie99.paper.manage.pojo.SyUser;
import com.shijie99.paper.manage.service.SyUserService;
import com.shijie99.paper.manage.util.Constant;

@Controller
public class LoginController {
	private static final String LOGIN_PAGE = "login";
	
	private static final String INDEX_PAGE = "main/index";
	
	@Autowired
	private SyUserService syUserService;
	
	@RequestMapping(value = {"/", "/index", "index.html", "index.html", "index.jsp"}, method = RequestMethod.GET) 
	public String index(HttpServletRequest request, HttpServletResponse response) {
		String page = login(request, response);
		return page;
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response) {
		SyUser user = (SyUser)request.getSession().getAttribute(Constant.SESSION_USER);
		if(user != null) {
			return INDEX_PAGE;
		} 
		return LOGIN_PAGE;
	}
	
	@RequestMapping(value = "/login.ajax", method = RequestMethod.POST)
	public void loginAjax(String username, String password, String rememberme, 
			HttpServletRequest request, HttpServletResponse response) {
						
		SyUser user = syUserService.queryUserByName(username);
		
		JSONObject retObj = new JSONObject();
		
		if(user != null) {
			if(user.getPassword().equals(password)){
				//写入session
				request.getSession().setAttribute(Constant.SESSION_USER, user);
				//返回json对象填充
				retObj.put("permission", "1");
			}else{
				retObj.put("permission", "0");
			}
		} else {
			retObj.put("permission", "0");
		}
		
		try {
			response.getWriter().write(retObj.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		//撤销session
		request.getSession().removeAttribute(Constant.SESSION_USER);
		
		return "redirect:/login";
	}
}
